package com.chenye.rmi;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.RemoteException;

/**
 * @Package: [com.chenye.rmi]
 * @Description: [一句话描述该类的功能]
 * @Author: [chenye]
 * @CreateDate: [2018/3/29 14:39]
 * @UpdateUser: [chenye(如多次修改保留历史记录，增加修改记录)]
 * @UpdateDate: [2018/3/29 14:39，(如多次修改保留历史记录，增加修改记录)]
 * @UpdateRemark: [说明本次修改内容, (如多次修改保留历史记录，增加修改记录)]
 * @Version: [v1.0]
 */
public class RmiSocketServer extends Thread implements TestService{
    @Override
    public String say(String str) throws RemoteException {
        return str;
    }

    @Override
    public String sayHi() throws RemoteException {
        return "sayHi";
    }
    @Override
    public void run() {
        try {
            // new socket at port 9000
            ServerSocket serverSocket = new ServerSocket(9090);
            // accept stub's request
            Socket socket = serverSocket.accept();
            while (socket != null) {
                // get stub's request
                ObjectInputStream inStream =
                        new ObjectInputStream(socket.getInputStream());
                String method = (String)inStream.readObject();
                // check method name
                if (method.equals("say")) {
                    // execute object server's business method
                    String age = this.say("say");
                    ObjectOutputStream outStream =
                            new ObjectOutputStream(socket.getOutputStream());
                    // return result to stub
                    outStream.writeObject(age);
                    outStream.flush();
                }
                if(method.equals("sayHi")) {
                    // execute object server's business method
                    String name = this.sayHi();
                    ObjectOutputStream outStream =
                            new ObjectOutputStream(socket.getOutputStream());
                    // return result to stub
                    outStream.writeObject(name);
                    outStream.flush();
                }
            }
        } catch(Throwable t) {
            t.printStackTrace();
//            System.exit(0);
        }
    }
    public static void main(String[] args){
        RmiSocketServer socketServer = new RmiSocketServer();
        socketServer.start();
    }
}
